package easy.trace.plugin.mybatis.define;

import easy.trace.agent.define.Instrumentation;
import easy.trace.core.util.StringUtils;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;

/**
 * @author easy
 */
public class MybatisInstrumentation implements Instrumentation {

    private static final String ENHANCE_TRANSFORM_CLASS = "org/apache/ibatis/session/Configuration";
    private static final String ENHANCE_CLASS = "org.apache.ibatis.session.Configuration";
    private static final String ENHANCE_METHOD = "()V";

    @Override
    public byte[] interceptPoints() {
        System.out.println("---------------transform start:" + ENHANCE_CLASS + "---------------");
        try {
            ClassPool classPool = ClassPool.getDefault();
            CtClass ctClass = classPool.getCtClass(ENHANCE_CLASS);
            // 加载和执行生成的类
            CtConstructor[] constructors = ctClass.getDeclaredConstructors();
            for (CtConstructor constructor : constructors) {
                if (constructor.getMethodInfo().getDescriptor().equals(ENHANCE_METHOD)) {
                    ctClass.removeConstructor(constructor);
                    constructor.insertAfter("{ this.interceptorChain.addInterceptor(new easy.trace.plugin.mybatis.MybatisInterceptor());}");
                    ctClass.addConstructor(constructor);
                }
            }
            System.out.println("---------------transform end:" + ENHANCE_CLASS + "---------------");
            return ctClass.toBytecode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public String getInterceptClass() {
        return ENHANCE_TRANSFORM_CLASS;
    }

    @Override
    public boolean check(String className) {
        if (StringUtils.isEmpty(className)) {
            return false;
        }
        if (ENHANCE_TRANSFORM_CLASS.equalsIgnoreCase(className)) {
            return true;
        }
        return false;
    }
}
